#include <iostream>
#include <string>

#include <cstdlib>
#include <cerrno>
#include <cstring>

#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[], char *env[])
{
    if (argc != 3)
    {
        std::cout << "\n"
                  << argv[0] << " ip port\n"
                  << std::endl;
        exit(1);
    }

    // 获取server的IP和PORT

    std::string serverIp = argv[1];
    uint16_t serverPort = atoi(argv[2]);

while(true)
{
    // 创建客户端对应的套接字
    int clientSock = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSock < 0)
    {
        fprintf(stderr, "socket error %d:%s\n", errno, strerror(errno));
        exit(2);
    }

    // 客户端不需要显示bind,直接进行获取连接即可
    struct sockaddr_in server;
    socklen_t serverSize = sizeof(server);
    memset((void *)&server, 0, serverSize);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    server.sin_addr.s_addr = inet_addr(serverIp.c_str());

    // while (true)
    // {
        if (connect(clientSock, (struct sockaddr *)&server, serverSize) < 0)
        {
            fprintf(stderr, "connect error %d:%s\n", errno, strerror(errno));
            exit(3);
        }

        char buffer[1024];
        bzero(buffer, sizeof(buffer));

        while (true)
        {
            std::string line;
            std::cout << "请输入$ ";
            std::getline(std::cin, line);

            // 发送数据
            if (send(clientSock, line.c_str(), line.size(), 0) < 0)
            {
                fprintf(stderr, "send error %d:%s\n", errno, strerror(errno));
                exit(4);
            }

            // 接收数据
            ssize_t n = recv(clientSock, (void *)buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = '\0';
                std::cout << buffer << std::endl;
                sleep(1);
                break;
            }
            else if (n == 0)
            {
                break;
            }
            else
            {
                break;
            }
        }
    // }
}
    return 0;
}